package edu.del.springbootredisbusinesspractice.commons.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;


@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建 RedisTemplate 对象 并放入到 连接工厂中
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 创建 Jackson2JsonRedisSerializer 对象，用于序列化
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);

        // 设置 RedisTemplate 的 key 序列化方式
        template.setKeySerializer(RedisSerializer.string());

        // 设置 RedisTemplate 的 haseKey 序列化方式
        template.setHashKeySerializer(RedisSerializer.string());

        // 设置 RedisTemplate 的 value 序列化方式
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        return template;
    }
}
